<?php
/**
%%%copyright%%%
 *
 * FusionTicket - ticket reservation system
 * Copyright (C) 2007-2008 Christopher Jenkins. All rights reserved.
 *
 * Original Design:
 *	phpMyTicket - ticket reservation system
 * 	Copyright (C) 2004-2005 Anna Putrino, Stanislav Chachkov. All rights reserved.
 *
 * This file is part of fusionTicket.
 *
 * This file may be distributed and/or modified under the terms of the
 * "GNU General Public License" version 2 as published by the Free
 * Software Foundation and appearing in the file LICENSE included in
 * the packaging of this file.
 *
 *
 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
 * THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE.
 *
 *
 * The "GNU General Public License" (GPL) is available at
 * http://www.gnu.org/copyleft/gpl.html.
 *
 * Contact info@noctem.co.uk if any conditions of this licencing isn't 
 * clear to you.
 
 */
?>
<?php
class User_Smarty {

  var $logged;

  function User_Smarty (&$smarty)
  {
    if(isset($_SESSION['_SHOP_USER'])){
      $user=$_SESSION['_SHOP_USER'];
      $this->_fill($user);
      $this->logged=true;
    }

    $smarty->register_object("user",$this);
    $smarty->assign_by_ref("user",$this);
    $smarty->assign("user_fields",array(
	  array('name'=>'user_id','mandatory'=>1,'short'=>0),
      array('name'=>'user_firstname','mandatory'=>1,'short'=>1),
      array('name'=>'user_lastname','mandatory'=>1,'short'=>1),
      array('name'=>'user_addresse','mandatory'=>1,'short'=>1),
      array('name'=>'user_addresse1','mandatory'=>0,'short'=>0),
      array('name'=>'user_zip','mandatory'=>1,'short'=>1),
      array('name'=>'user_city','mandatory'=>1,'short'=>1),
	  array('name'=>'user_state','mandatory'=>1,'short'=>1),
      array('name'=>'user_country','mandatory'=>1,'short'=>1),
      array('name'=>'user_email','mandatory'=>1,'short'=>0),
      array('name'=>'user_phone','mandatory'=>0,'short'=>0),
      array('name'=>'user_fax','mandatory'=>0,'short'=>0)
    ));
  }


  function login ($params){
  	if($id=$this->login_f($params['username'],$params['password'])){
		echo "<script>window.location.href='{$params['uri']}';</script>"; exit;	
	}
	/*header("location: index.php?action=loginerror&register_user=on");*/
  }

  function login_f ($username, $password){
    require_once('classes/ShopDB.php');
    $query="select auth.username,User.* 
            from auth,User 
	    where auth.user_id=User.user_id 
	      and username=".ShopDB::quote($username)."
	      and password='".md5($password)."'
     	  and user_status=2
		  LIMIT 1";
		  
	$query2 = "SELECT active 
		FROM auth,User 
		WHERE username=".ShopDB::quote($username)." 
		AND password='".md5($password)."' 
		AND user_status=2 LIMIT 1";
		$check=ShopDB::query($query2);
		$active=mysql_fetch_assoc($check);
	if(!$active['active']==NULL) {
		$log_error = "<p>This account hasnt been activated yet.<br />Please activate your account!</p> \n";
		$log_error .= "<p>Please check your email for the activation email. Also check your spam folder. Then follow the link to activate your account</p>";
		$log_error .= "<p>If you still haven't recieved anything after a hour please click <a href=\"resend_activation.php\"<b>here</b></a> to resend activation email.";
		$_SESSION['ERROR']=$log_error;
		header("location:  index.php?action=loginerror&register_user=on");
		return FALSE;
	}
	if($result=ShopDB::query($query) and $user=mysql_fetch_assoc($result)){
	  	$user['is_member']=true;    
      	$_SESSION['_SHOP_USER']=$user;
      	$this->_fill($user);
      	$this->logged=true;
      	$this->is_member=true;
      	return $user['user_id'];
	}
	$log_error = "Wrong username or password! Please try again, remembering that the username and password are case sensitive.<br />";
	$log_error .= "If you have forgoten your username or password please click <a href=\"forgot_password.php\"><strong>here</strong></a>";
	$_SESSION['ERROR']=$log_error;
	header("location:  index.php?action=loginerror&register_user=on");
	return FALSE;
  
  }

  function logout ($params,&$smarty){
    $this->logout_f();
  }

  function logout_f (){
    $this->_clean();
    unset($_SESSION['_SHOP_USER']);
  }
  
 /* User data gets subbmitted to here */ 
  function member ($params,&$smarty){
    if(!$this->member_f($params['data'],$err,$params['mandatory'])){
      $smarty->assign('user_errors',$err);
    }
  }

/*The next bit of code creates users */
  function member_f (&$member,&$err,$login=TRUE,$mandatory_l=0){
    require_once('functions/user_func.php');

	if(!empty($mandatory_l)){
		if(preg_match_all('/\w+/',$mandatory_l,$matches)){
			$mandatory=$matches[0];
		}
	}
		
    if($res = create_member($member,$err,$mandatory)){ /* $res == the returned $user_id from create_member in user_func.php */
	  header("location: index.php?action=activate&register_user=on");
      return $res;
    }  
  }
///////////////////
//Update Member Function!
/////////////////////

  function update_member($params,&$smarty){
  	if(!$this->update_member_f($params['data'],$err,$params['mandatory'])){
		$smarty->assign('user_errors',$err);
	}
  }
  
  function update_member_f (&$member,&$err,$login=TRUE,$mandatory_l=0){
    require_once('functions/user_func.php');

		if(!empty($mandatory_l)){
		  if(preg_match_all('/\w+/',$mandatory_l,$matches)){
			  $mandatory=$matches[0];
			}
		}
		
    if($res = update_member2($member,$err,$mandatory)){ /* $res == the returned $user_id from create_member in user_func.php */
      $this->login_f($member['user_email'],$member['password1']);
	  $_SESSION['_USER_UPDATED']="User Information updated successfully!";
	  //header("location: index.php?personal_page=details");
      return $res;
    }
	return false;
  }

///////////////////
///////Guest///////
///////////////////
// Guest Don't use this code anymore. Its for purchases without having to log on.
  function guest ($params,&$smarty){
    if(!$this->guest_f($params['data'],$err,$params['short'],$params['mandatory'])){
      $smarty->assign('user_errors',$err);
    }
  }

  function guest_f (&$guest,&$err,$short=FALSE,$mandatory_l=0){
    require_once('functions/user_func.php');
		if(!empty($mandatory_l)){
		  if(preg_match_all('/\w+/',$mandatory_l,$matches)){
			  $mandatory=$matches[0];
			}
		}
    if($guest_id = create_guest($guest,$err,$short,$mandatory)){
      $this->_login_guest($guest_id);
      return $guest_id;
    }  
  }
/////////////////
/////////////////  
  function forgot_password ($params,&$smarty){
    $this->forgot_password_f($params['email'],$params['template']);
  }

  function forgot_password_f ($email,$tpl=''){
    global $_SHOP;
  
    $pwd = substr(md5(uniqid(rand())), 0, 8);
    $pwd_md5=md5($pwd);
    
    require_once("classes/ShopDB.php");
    
    $query="SELECT * from auth,User where username=".ShopDB::quote($email)." and auth.user_id=User.user_id";
    if(!$row=ShopDB::query_one_row($query)){
      return FALSE;
    }
    
    $query="UPDATE auth SET password='$pwd_md5' WHERE username=".ShopDB::quote($email)." limit 1";

    if(ShopDB::query($query) and mysql_affected_rows()==1){
      require_once("classes/TemplateEngine.php");
      require_once("classes/htmlMimeMail.php");

      $engine= new TemplateEngine();
			if(empty($tpl)){
			  $tpl='forgot_passwd';
			}
      $tpl=$engine->getTemplate($tpl,$_SHOP->organizer_id);
      $email=&new htmlMimeMail();

      $row['new_password']=$pwd;
      $tpl->build($email,$row);
 
      if($email->send($tpl->to)){
        return true;
      }  
    }
  }
  
  	function resend_activation($params,&$smarty){
  		$this->forgot_password_f($params['email'],$params['template']);
	}
	
	function resend_activation_f($email,$tpl=''){
		global $_SHOP;
		
		$query="SELECT * FROM auth,User WHERE username=".ShopDB::quotei($email)." and auth.user_id=User.user_id";
		// Cheacks for a realy user.
	    if(!$row=ShopDB::queryi_one_row($query)){
	    	echo("#ERR-NOUSR");
    		return FALSE;
    	}
    	//Checks to see if allready activated, if has been activated then return.
    	if($row['active']==null){
    		echo("#ERR-ISACT");
			return FALSE;
		}
		
		$active = md5(uniqid(rand(), true));
		$user_id=$row['user_id'];
		$query="UPDATE `auth` SET active='$active' WHERE username=".ShopDB::quotei($email)." LIMIT 1";
		
		if(ShopDB::queryi($query) and mysqli_affected_rows($_SHOP->link)==1){
			require_once("classes/TemplateEngine.php");
      		require_once("classes/htmlMimeMail.php");
      	
       		$email=$_POST['user_email'];
			$engine= new TemplateEngine();
				if(empty($tpl)){
					$tpl='Signup_email';
				}
			$tpl=$engine->getTemplate($tpl,$_SHOP->organizer_id);
			$email=&new htmlMimeMail();

			$link= $_SHOP->root."/index.php?register_user=on&action=activate&x=".$user_id."&y=".$active;
			$row['link']=$link;
			$tpl->build($email,$row);
 
			if($email->send($tpl->to)){
				return TRUE;
			}else{
				echo("#ERR-SNDERR");
				return FALSE;
			}
		}
	}
  
  function _fill ($user){ ///????
    $this->_clean();
    foreach($user as $k=>$v){
      $this->$k=$v; /// What does this do? Sets User_Smary->$k as $v ?
    }
  }

  function _clean (){
    $user=(array)$this;
    foreach($user as $k=>$v){
      unset($this->$k);
    }
  }
  
  	function login_guest($params,&$smarty){
		if(!$this->_login_guest($params['user_id'])){
			return;
		}
	}

  function _login_guest ($user_id){
    require_once('classes/ShopDB.php');
    $query="SELECT * 
			FROM `User` 
	    	WHERE user_id=".ShopDB::quotei($user_id)." 
	      	AND user_status=3
	    	LIMIT 1";
      

    if($result=ShopDB::queryi($query) and $user=mysqli_fetch_assoc($result)){
      $user['is_guest']=true;
      $_SESSION['_SHOP_USER']=$user;
      $this->_fill($user);
      $this->logged=true;
      $this->is_guest=true;
      return $user['user_id'];
    }
    
    return FALSE;
  
  }

}
?>